package com.usian.app.filter;

import com.usian.app.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {


    /**
     * filter 进行token的校验
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1:拿到token
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //2: 解密判断token ？通过 过滤器放行  未通过 拦截返回一个自定义的错误码

        //2.1.判断当前的请求是否为登录，如果是，直接放行
        if(request.getURI().getPath().contains("/login/login_auth")){
            //放行
            return chain.filter(exchange);
        }

        //2.2.判断token不能为空
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //2.3: 不为空的token 进行解密、获取值、放到下游服务请求的请求头中
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);

            if(result == 0 || result == -1){
                //jwt 校验token 是有效的
                Integer userId =(Integer) claims.get("id");
                log.info("find userid:{} from uri:{}",userId,request.getURI());
                //jwt 解密出来的token（apuser表的主键id）值，放入到下游请求头
                ServerHttpRequest serverHttpRequest = request.mutate().headers(s -> {
                    s.add("userId", userId + "");
                }).build();

                //放行过滤器
                exchange.mutate().request(serverHttpRequest).build();
            }
        }catch (Exception e){
            log.info(e.getMessage());
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
